package com.litxuf.logic.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BaseBusException extends org.springframework.core.NestedRuntimeException {
	private final static ApplicationContextUtil oct = ApplicationContextUtil.getContext();

	private String description = "";

	private String key = "";

	private final String KEY_PREFIX = "@";

	private Object[] paras = null;

	private Locale locale = null;

	private ArrayList subExceptions = null;
	

	protected final Log log = LogFactory.getLog(BaseBusException.class);

	public BaseBusException(String key, Object[] parase, String defautlMessage,Locale local) {

		super("");
		this.key = key;
		this.locale = (local != null) ? local : Locale.getDefault();
		this.paras = parase;
		//this.defautlMessage = defautlMessage;
		//System.out.println("errorMsgKey:" + key);
		this.description = oct.getMessage(key, paras, defautlMessage,locale);

	}

	public String getDescription() {
		return description;
	}

	public String getKey() {
		return key;
	}

	public String getMessage() {
		return super.getMessage() + ": " + this.getDescription();
		// return super.getMessage() + "; " + this.getKey() + ":" +
		// this.getDescription();
	}

	public Object[] getParas() {
		return paras;
	}

	/** ***返回paras对应的资源文件内的内容******* */
	public Object[] getParsedParas() {
		Object[] obj = null;
		if (paras != null) {
			obj = new Object[paras.length];
			for (int i = 0; i < paras.length; i++) {
				if (paras[i] != null && (paras[i] instanceof String) && paras[i].toString().startsWith(KEY_PREFIX)) {
					obj[i] = oct.getMessage(((String) paras[i]).substring(1), null, locale);
				} else {
					obj[i] = paras[i];
				}
			}
		}

		return obj;

	}

	public static void main(String[] args) {

		// System.out.println("exception:------" + oct.getMessage("errors.msg1",
		// new Object[] { "gao", "xiang" }, Locale.getDefault()));
		try {
			throw new BaseBusException("sql.", new String[] { "nin1", "hao1" }, "999999999", null);
		} catch (BaseBusException ex) {
			System.out.println("desc:" + ex.getDescription());
		//	System.out.println("message:" + ex.getMessage());
		}
	}

	/**
	 * @return
	 */
	public List getSubExceptions() {
		return subExceptions;
	}

	public void addBaseRuntimeException(BaseBusException ex) {
		if (subExceptions == null) {
			subExceptions = new ArrayList();
		}
		subExceptions.add(ex);
	}

}
